package com.allen.controller;

import com.allen.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author dragon1006xu@gmail.com
 * @create 2022/2/17 20:46
 */
@Slf4j
@RequestMapping("/common")
@RestController
public class CommonFileUploadController {
    //文件上传保存目录
    @Value("${reggie.upload-path}")
    private String uploadPath;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //1.获取原文件名称 得到其后后缀
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //2.设置上传文件的新文件名【防止和之前的文件名同名 导致被覆盖】
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        //拼接得到完整的文件名称 包含后缀
       newFileName= newFileName+ suffix;
       //3.判断文件上传目录是否存在 如果不存在，创建一个
        File directory = new File(uploadPath);
        if (directory.exists()) {
            directory.mkdir();
        }
        //4.设置文件上传的保存位置
        File newFile = new File(uploadPath + newFileName);
        //5.将上传的文件保存到指定位置
        file.transferTo(newFile);
        //6.返回上传成功 文件上传之后会进行下载 所以上传成功响应给前端的数据应该是文件名称
        return R.success(newFileName);
    }

    //文件下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response)  {
        try {
            //输入流 通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(uploadPath + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            //定义一个变量，记录读取到的字节个数
            int len=0;
            //定义一个字节数组，存储读取到的字节数据
            byte[] bytes = new byte[1024];
            //循环读写
            while ((len=fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
